package model

import (
	Mysql "gin/database"
	"github.com/Gre-Z/common/jtime"
	"gorm.io/datatypes"
	"time"
)

type Media struct {
	Id      int64            `json:"id" gorm:"column:id"`
	Md5Name string           `json:"md5_name" gorm:"column:md5_name"`
	Md5     string           `json:"md5" gorm:"column:md5"`
	Type    string           `json:"type" gorm:"column:type"`
	Status  string           `json:"status" gorm:"column:status"`
	Param   datatypes.JSON   `json:"param" gorm:"column:param"`
	Created jtime.TstampTime `json:"created" gorm:"column:created"`
	Uuid    string           `json:"uuid" gorm:"column:uuid"`
}

// 设置表名
func (Media) TableName() string {
	return "media"
}

// 获取指定文件MD5数据
func (this *Media) GetMediaDataByMD5(MD5 string) (mediaData Media, err error) {

	result := Mysql.DB.Where("md5 = ?", MD5).First(&this)

	if this.Id == 0 {
		err = result.Error
	} else {
		mediaData = *this
	}

	return
}

// 插入媒体数据
func (this *Media) Insert() (id int64, err error) {
	result := Mysql.DB.Create(&this)
	id = this.Id
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// 获取指定文件MD5数据
func (this *Media) GetMediaDataByMD5Name(MD5 string) (mediaData Media, err error) {

	result := Mysql.DB.Where("md5_name = ?", MD5).First(&this)

	if this.Id == 0 {
		err = result.Error
	} else {
		mediaData = *this
	}

	return
}

// 更新文件状态通过 Md5Name
func (this *Media) UpdateStatusByMd5Name(Md5Name string, Status string) (err error) {
	result := Mysql.DB.Model(&this).
		Where("md5_name = ?", Md5Name).
		Update("status", Status)

	if result.Error != nil {
		err = result.Error
	}
	return
}

// 通过Md5 Name 查找媒体
func (this *Media) SelectMediaByMd5Name(Md5Name []string) (mediaData []Media, err error) {

	result := Mysql.DB.Where("md5_name in (?)", Md5Name).Find(&mediaData)

	if result.Error != nil {
		err = result.Error
	}

	return
}

// 通过Md5 Name 查找半天过去了还没有被删除的数据
func (this *Media) FindHalfDayMediaByMd5Name(Md5Name string) (mediaData Media, err error) {

	db := Mysql.DB
	db = db.Where("md5_name = ?", Md5Name)
	halfDayTimestamp := time.Now().Unix() - 43200
	db = db.Where("created <= ?", halfDayTimestamp)

	db = db.Select("id,md5_name,md5,type,status,param")

	result := db.First(&mediaData)

	if result.Error != nil {
		err = result.Error
	}

	return
}

// 文件重试提交，更新文件创建时间通过 Md5Name
func (this *Media) UpdateHalfDayMediaCreatedByMd5Name(Md5Name string) (err error) {
	result := Mysql.DB.Model(&this).
		Where("md5_name = ?", Md5Name).
		Update("created", jtime.TstampTime(time.Now().Unix()))

	if result.Error != nil {
		err = result.Error
	}
	return
}

// 通过Md5 Name 删除媒体
func (this *Media) RemoveMediaByMd5Name(Md5Name []string) (err error) {
	result := Mysql.DB.Where("md5_name in (?)", Md5Name).Delete(&this)

	if result.Error != nil {
		err = result.Error
	}
	return
}
